<?php
/**
 * 验证身份证号码
 */
!defined('IN_FRAME') && die('404 Page');
class SFZ {
    
    private static function idcard_verify_number($idcard_base) {
        $re = '';
        if (strlen($idcard_base) == 17) {
            $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 加权因子
            $arr = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); // 校验码对应值
            $checksum = 0;
            for ($i = 0; $i < 17; $i ++) {
                $checksum += substr($idcard_base, $i, 1) * $factor[$i];
            }
            $re = $arr[$checksum % 11];
        }
        return $re;
    }
    
    private static function idcard_15to18($idcard) {
        $re = '';
        if (strlen($idcard) == 15) {
            $i = (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) ? 18 : 19;
            $idcard = substr($idcard, 0, 6) . $i . substr($idcard, 6, 9);
            $re = $idcard . self::idcard_verify_number($idcard);
        }
        return $re;
    }
    
    private static function idcard_checksum18($idcard) {
        $re = false;
        if ($idcard && strlen($idcard) == 18) {
            $re = (self::idcard_verify_number(substr($idcard, 0, 17)) == strtoupper(substr($idcard, 17, 1)));
        }
        return $re;
    }
    
    public static function check($idcard) {
        strlen($idcard) == 15 && $idcard = self::idcard_15to18($idcard);
        return self::idcard_checksum18($idcard);
    }
}